using System;
using Microsoft.TeamFoundation.Server;
using TXLooker.Common;
using TXLooker.Common.Core;

namespace TXLooker.Core
{
    internal class ProjectProvider : SelfUpdater
    {
        private ProjectProvider()
        { }
        public ProjectProvider( ServerProvider parent, ProjectInfo projectInfo ) : this()
        {
            this.ServerProvider = parent;
            this.ProjectUri = new Uri(projectInfo.Uri);
            this.ProjectName = projectInfo.Name;
        }

        #region IProjectProvider Members

        public ServerProvider ServerProvider
        {
            get { return this.m_server; }
            protected set
            {
                this.m_server = value;
            }
        }
        private ServerProvider m_server = null;

        #region Project Name

        public string ProjectName
        {
            get { return this.m_name; }
            protected set
            {
                if( value == this.m_name )
                    return;

                this.m_name = value;

                this.RaiseProjectNameChanged();
            }
        }
        private string m_name = null;

        public event EventHandler ProjectNameChanged
        {
            add { lock( this.m_syncProjectName ) { this.m_OnProjectNameChangedEH += value; } }
            remove { lock( this.m_syncProjectName ) { this.m_OnProjectNameChangedEH -= value; } }
        }
        private EventHandler m_OnProjectNameChangedEH = null;

        private readonly object m_syncProjectName = new object();

        private void RaiseProjectNameChanged()
        {
            CommonGlobal.RaiseEventHandler( this.m_OnProjectNameChangedEH, new object[] { this, EventArgs.Empty }, this.m_syncProjectName );
        }

        #endregion Project Name

        #region Project Uri

        public Uri ProjectUri
        {
            get { return this.m_uri; }
            protected set
            {
                this.m_uri = value;
            }
        }
        private Uri m_uri = null;

        #endregion Project Uri

        public ProjectInfo GetProjectInfo()
        {
            ProjectInfo project = null;

            try
            {
                ICommonStructureService structure = this.ServerProvider.CommonServerStructure;

                if( structure != null )
                    project = structure.GetProject( this.ProjectUri.ToString() );
            }
            catch
            { }

            return project;
        }

        protected override void UpdateData()
        {
            try
            {
                ProjectInfo project = this.GetProjectInfo();
                this.ProjectName = project.Name;
            }
            catch
            { }
        }

        #endregion
    }
}
